/*************************************
DataLogger004

T.Bristow
24/11/12

Reads from 4 connected sensors and sends
the data over the serial port according
to TN001A Prototype dataLogger004 Protocol

*************************************/

#include <stdio.h>

#define sensor1 A0
#define sensor2 A1
#define sensor3 A3
#define sensor4 A4

char buffer[129];
char * bufferPos=buffer;
long lastMeasure=0;
char lines=0;

void setup(void){
  
  Serial.begin(19200);
  
  pinMode(6,INPUT);
  
  // Wait until the initialisation character (0xF0) has been received
  while(1){
	if(Serial.available()&&Serial.read()==0xF0) break;
	if(digitalRead(6)==HIGH) break;
  }
}

void loop(void){
  short s1,s2,s3,s4;
  
  // wait until at least 100 milliseconds has passed since the last measurement (10 measurements a second)
  while(millis()<lastMeasure+100);
  
  // Read analog voltages from the sensors
  s1=analogRead(sensor1);
  s2=analogRead(sensor2);
  s3=analogRead(sensor3);
  s4=analogRead(sensor4);
  
  // Write the data to the buffer
  bufferPos+=sprintf(bufferPos,"%lu,%d,%d,%d,%d\r\n",millis(),s1,s2,s3,s4);

  if(++lines==4){
    bufferPos=buffer; // reset bufferPos to the start of buffer
    Serial.print(buffer);
    Serial.flush();
    lines=0;
  } 
  lastMeasure=millis();
}
